package org.epidroid.epidroid.epirss;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.NodeList;

import android.util.Log;

public class LoadRss {
	private String FeedUrl;

	public LoadRss(String feedUrl)
	{
		this.FeedUrl = feedUrl;
	}

	protected String getNodeValue(org.w3c.dom.Element entry, String name)
	{
		org.w3c.dom.Element nodeElement = (org.w3c.dom.Element) entry.getElementsByTagName(name).item(0);
		return nodeElement.getFirstChild().getNodeValue();
	}

	public RssArticle LoadArticle(org.w3c.dom.Element entry)
	{
		String title = getNodeValue(entry, "title");
		String description = getNodeValue(entry, "summary");
		String content = ((org.w3c.dom.Element) entry.getElementsByTagName("content").item(0)).getTextContent();
		String link = ((org.w3c.dom.Element) entry.getElementsByTagName("link").item(0)).getAttribute("href");
		String published = getNodeValue(entry, "published").replace("T", " ").replace("Z", "");

		// create article
		return new RssArticle(title, description, content, link, published);
	}

	public List<RssArticle> LoadFeed() throws Exception
	{
		List<RssArticle> articles = new ArrayList<RssArticle>();

		// open an URL connection make GET to the server and take xml RSS data
		URL url = new URL(FeedUrl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();

		if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
			InputStream is = conn.getInputStream();

			// DocumentBuilderFactory, DocumentBuilder are used for xml parsing
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();

			// using db (Document Builder) parse xml data and assign it to Element
			org.w3c.dom.Document document = db.parse(is);
			org.w3c.dom.Element element = document.getDocumentElement();

			// take rss nodes to NodeList
			NodeList nodeList = element.getElementsByTagName("entry");

			if (nodeList.getLength() > 0) {
				for (int i = 0; i < nodeList.getLength(); i++) {
					try {
						RssArticle article = LoadArticle((org.w3c.dom.Element) nodeList.item(i));
						articles.add(article);
						Log.d("EpiDroid", "Article loaded: " + article.title);
					} catch (Exception e) {
						Log.w("EpiDroid", "Could not load an article. " + e.toString());
					}
				}

				conn.disconnect();
				return (articles);
			} else {
				conn.disconnect();
				throw new Exception ("Couldn't fetch the feed! (err 0x30)");
			}
		} else {
			conn.disconnect();
			throw new Exception ("Couldn't fetch the feed! (err 0x20)");
		}
	}
}
